﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PSE.Framework.Communication.Adapters.File;
using PSE.Framework.Communication.Configuration.Adapters.File;
using PSE.Framework.Communication.Messages;
using PSE.Framework.Communication.Adapters;
using PSE.Framework.Communication.Messages.Adapters;

namespace PSE.Framework.Communication.Client.File
{
    /// <summary>
    /// Classe base dos clients de importação de arquivos
    /// </summary>
    /// <typeparam name="TOpenParameter">Tipo do parâmetro de abertura do processo</typeparam>
    public abstract class SyncFileInputClient<TOpenParameter> : BaseInputClient<TOpenParameter>
        where TOpenParameter : class
    {
        #region Construtores
        /// <summary>
        /// Construtor padrão
        /// </summary>
        public SyncFileInputClient()
        {
        }
        #endregion

        #region Adapter
        /// <summary>
        /// Adapter encapsulado pelo client
        /// </summary>
        protected new ISyncFileInputAdapter Adapter
        {
            get { return (ISyncFileInputAdapter)base.Adapter; }
        }
        #endregion

        #region FileStatus
        /// <summary>
        /// Status da importação do arquivo
        /// </summary>
        public FileStatus FileStatus
        {
            get
            {
                if (this.Adapter != null)
                {
                    switch (this.Adapter.StreamStatus)
                    {
                        case StreamStatus.Created:
                            return FileStatus.Created;
                        case StreamStatus.Opened:
                            return FileStatus.Opened;
                        case StreamStatus.Closed:
                            return FileStatus.Closed;
                        default:
                            return FileStatus.Created;
                    }
                }
                else
                {
                    return FileStatus.Created;
                }
            }
        }
        #endregion

        #region CreateProcess
        /// <summary>
        /// Cria o processo de comunicação
        /// </summary>
        /// <param name="process">Nome do processo</param>
        protected override void CreateProcess(string process, object parameter)
        {
            base.CreateProcess(process, parameter);

            this.Adapter.NewFileCreated += new EventHandler<FileCreatedEventArgs>(Adapter_NewFileCreated);
        }

        void Adapter_NewFileCreated(object sender, FileCreatedEventArgs e)
        {
            this.OnNewFileCreated(new FileCreatedEventArgs(e.FilePath));
        }

        #endregion

        public int OpenFile()
        {
            this.VerifyIsOpened();

            return this.Adapter.OpenStream();
        }

        public int OpenFile(FileReceiveParameter parameter)
        {
            this.VerifyIsOpened();

            return this.Adapter.OpenStream(parameter);
        }

        public RecordInfo ReadRecord()
        {
            this.VerifyIsOpened();

            MessageInfo msg = this.Adapter.Receive();

            if (msg != null)
                return new RecordInfo(msg);
            else
                return null;
        }

        public IEnumerable<RecordInfo> ReadAllRecords()
        {
            this.VerifyIsOpened();

            return this.Adapter.ReceiveAll().Select<MessageInfo, RecordInfo>(m => new RecordInfo(m));
        }

        public IEnumerable<RecordInfo> ReadAllRecords(FileReceiveParameter parameter)
        {
            this.VerifyIsOpened();

            return this.Adapter.ReceiveAll(parameter).Select<MessageInfo, RecordInfo>(m => new RecordInfo(m));
        }

        public virtual void CloseFile()
        {
            this.VerifyIsOpened();

            this.Adapter.CloseStream();
        }

        #region CancelFile
        /// <summary>
        /// Cancela a importação do arquivo
        /// </summary>
        public virtual void CancelFile()
        {
            this.VerifyIsOpened();

            this.Adapter.CancelStream();
        }
        #endregion

        #region CloseProcess
        /// <summary>
        /// Fecha o processo de comunicação
        /// </summary>
        /// <param name="process">Nome do processo</param>
        protected override void CloseProcess()
        {
            base.CloseProcess();

            // Limpando processo
            this.Adapter.NewFileCreated -= new EventHandler<FileCreatedEventArgs>(Adapter_NewFileCreated);
        }
        #endregion

        #region NewFileCreated
        /// <summary>
        /// Evento disparado quando um registro é lido
        /// </summary>
        public event EventHandler<FileCreatedEventArgs> NewFileCreated;

        /// <summary>
        /// Dispara evento RecordRead
        /// </summary>
        /// <param name="e">Argumento do evento</param>
        protected virtual void OnNewFileCreated(FileCreatedEventArgs e)
        {
            if (e == null)
                throw new ArgumentNullException("e");

            if (NewFileCreated != null)
            {
                NewFileCreated(this, e);
            }
        }
        #endregion
    }
}
